import paho.mqtt.client as mqtt
from api import config
import re

from logger.logger import Log


def on_connect(client, userdata, flags, rc):
    if str(rc) == "0":
        print("Connected Mqtt Broker Success ")
    client.subscribe("/rexsense/liuzh/#")


def on_message(client, userdata, msg):
    pass


class MqttClient:

    # 解析传入的消息内容，提取主题和载荷信息后，通过 MQTT 客户端向指定主题发布消息
    # 通过正则表达式提取 msg 中 'topic:' 和 'payload:' 之间的内容，分别赋值给 topic 和 payload 变量，使用 self.client.publish(topic, payload) 方法来向指定主题 topic 发布消息 payload
    def send_msg(self, msg):
        topic = re.findall(r'(?<=topic:).+(?=payload)', msg)[0]
        payload = re.findall(r'(?<=payload:).+', msg)[0]
        Log.logger.info("topic:")
        Log.logger.info(topic)
        Log.logger.info("payload:")
        Log.logger.info(payload)
        self.client.publish(topic, payload)

    def start(self):
        self.client = mqtt.Client()
        self.client.username_pw_set(config.Config.arg['Mqtt']['username'], config.Config.arg['Mqtt']['password'])
        self.client.on_connect = on_connect
        self.client.on_message = on_message
        self.client.connect(config.Config.arg['Mqtt']['host'], config.Config.arg['Mqtt']['port'], 60)
        self.client.loop_forever()

    def __init__(self):
        self.client = None


if __name__ == '__main__':
    pass
